package com.piper.email.service.abstractImpl;

import com.piper.email.entity.Email;
import com.piper.email.service.IEmailService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.util.HashSet;
import java.util.Set;

/**
 * 抽象邮箱服务
 */
@Slf4j
@Data
public abstract class AbstractEmailService implements IEmailService {

    private int weight = 1;

    private Set<String> cantReachMail = new HashSet<>();

    private AbstractEmailService nextService;

    @Override
    public boolean sendEmail(Email email) {
        // 判断此封邮件是否已经处理过
        Set<IEmailService> processedService = email.getProcessedService();
        if (processedService.contains(this)) {
            log.error("无满足条件服务 推送邮件：{}", email);
            return false;
        }
        processedService.add(this);

        // 判断是否能够处理 不能处理传递到下个服务
        String toAddress = email.getToAddress();
        boolean cantReach = this.getCantReachMail().contains(toAddress.substring(toAddress.lastIndexOf("@") + 1, toAddress.lastIndexOf(".")));
        if (cantReach) {
            return this.getNextService().sendEmail(email);
        }

        // 发送邮件
        return this.sendEmail(toAddress, email.getSubject(), email.getHtmlBody(), email.getTextBody());
    }

    /**
     * 发送邮件
     *
     * @param toAddress 到达邮箱
     * @param subject   标题
     * @param htmlBody  网页邮件
     * @param textBody  文字邮件
     * @return true成功
     */
    public abstract boolean sendEmail(String toAddress, String subject, String htmlBody, String textBody);
}
